package com.tangzhe.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 监听器，监听三大域
 */
public class MyListener implements ServletContextListener,
        HttpSessionListener, ServletRequestListener {


    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("容器初始化");

        //获取在web.xml中初始化的属性
        String contextInitParam = servletContextEvent.getServletContext().getInitParameter("contextInitParam");
        System.out.println(contextInitParam);

        //设置context域属性
        servletContextEvent.getServletContext().setAttribute("contextParam", "contextParam");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("容器销毁了");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("request销毁了");
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        System.out.println("request初始化");
        servletRequestEvent.getServletRequest().setAttribute("reqInitParam", "reqInitParam");
        System.out.println(servletRequestEvent.getServletRequest().getParameter("name2"));  //乱码
    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("session创建了");
        httpSessionEvent.getSession().setAttribute("sessionInitParam", "sessionInitParam");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("session销毁了");
    }
}











